package service

import (
	"SecKill/common/define"
	"SecKill/common/models"
	"SecKill/common/response"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"strconv"
)

func SaveBlog(c *gin.Context) {
	var blog models.Blog
	if err := c.ShouldBindJSON(&blog); err != nil {
		response.ResponseFail(c)
		return
	}
	if err := models.Db.Create(&blog).Error; err != nil {
		response.ResponseFail(c)
		return
	}
	response.ResponseOKWithData(c, "Success", blog.Id, 1)
}

func LikeBlog(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	models.Db.Model(new(models.Blog)).Where("id = ?", id).Update("liked", gorm.Expr("liked + ?", 1))
	response.ResponseOK(c)
}
func QueryMyBlog(c *gin.Context) {
	userId, _ := c.Get("userId")
	pageNum, _ := strconv.Atoi(c.DefaultQuery("current", strconv.Itoa(define.DEFAULT_PAGE_NUM)))
	pageSize := define.DEFAULT_PAGE_SIZE
	var blogs []models.BlogVo
	var count int64
	db := models.Db.Model(new(models.Blog)).
		Table("tb_blog b").
		Select("b.*,u.nick_name name,u.icon icon").
		Joins("left join tb_user u on b.user_id = u.id").
		Order("liked desc")
	db.Count(&count)
	db.Offset((pageNum-1)*pageSize).
		Limit(pageSize).
		Where("user_id = ?", userId).
		Find(&blogs)
	response.ResponseOKWithData(c, "Success", blogs, int(count))
}
func QueryHotBlog(c *gin.Context) {
	pageNum, _ := strconv.Atoi(c.DefaultQuery("current", strconv.Itoa(define.DEFAULT_PAGE_NUM)))
	pageSize := define.DEFAULT_PAGE_SIZE
	var blogs []models.BlogVo
	var count int64
	db := models.Db.Model(new(models.Blog)).
		Table("tb_blog b").
		Select("b.*,u.nick_name name,u.icon icon").
		Joins("left join tb_user u on b.user_id = u.id").
		Order("liked desc")
	db.Count(&count)
	db.Offset((pageNum - 1) * pageSize).
		Limit(pageSize).
		Find(&blogs)
	response.ResponseOKWithData(c, "Success", blogs, int(count))

}
